iT邦幫忙

2024 iThome 鐵人賽

DAY 20
0
佛心分享-刷題不只是刷題

CPE C++ 刷題系列 第 20

CPE C++ 刷題 Day 20

  • 分享至 

  • xImage
  •  

今天來解YKL21(UVA10922):2 the 9s

2 the 9s

https://ithelp.ithome.com.tw/upload/images/20241004/201555741yeSTzLlNN.png

主要是判斷輸入是不是9的倍數
如果是的話,再計算 9-degree

EX:
input 999999999999999999999
1.計算所有位數的和: 9+9+...9+9 = 189
2.189還不是個位數,所以繼續: 1+8+9 = 18
3.18也還不是個位數,1+8 = 9
4.最後9是個位數,進行了3次遞迴計算
5.輸出 3

#include <iostream>
#include <string>
using namespace std;

int nineDegree(int sum) {
    int degree = 1;
    while (sum >= 10) {
        int degree_sum = 0;
        
        while (sum > 0) {
            degree_sum += sum % 10;  
            sum /= 10;
        }
        sum = degree_sum;  
        degree++;  
    }
    return degree;
}
int main(){
	string str;
	while(cin >> str){
		int sum=0;
		
		if(str=="0")break;
		for(int i=0;i<str.size();i++){
			sum+=str[i] - '0';
		}
		if(sum%9==0){
			int count =0;
			int N = nineDegree(sum);
			cout << str << " is a multiple of 9 and has 9-degree " << N << "." << endl;
		}else{
			cout << str << " is not a multiple of 9." << endl;
		}
	}
	return 0;
}

上一篇
CPE C++ 刷題 Day 19
系列文
CPE C++ 刷題20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言